#! /usr/local/bin/python
# -*- coding: utf-8 -*-

' dar: dynamic active record simulator '

__author__ = 'rereadyou'

import db
import MySQLdb

class Dar:
    def __new__(cls, *args, **kwargs):
        return super(Dar, cls).__new__(cls, *args, **kwargs)

    def __init__(self, table):
        self.config = db
        self.conn = MySQLdb.connect(host=db.host, port=db.port,
            user=db.user, db=db.db, charset=db.charset)
        self.conn.autocommit(True)
        self.cursor = self.conn.cursor(MySQLdb.cursors.DictCursor)
        self.table = '%s%s' % (self.config.prefix, table)
        self.attributes = {}
        self.getColumns();

    def getColumns(self):
        sql = 'show columns from %s' % (self.table)
        self.exe(sql)
        columns = self.cursor.fetchall()
        for column in columns:
            self.attributes[column['Field']] = column['Default']

    def load(self, datas):
        for k, v in datas.items():
            if self.attributes.has_key(k):
                self.attributes[k] = v 

    def saveOn(self, datas={}, on={}):
        if datas:
            self.load(datas)
        dar = {}
        if on:
            dar = self.one(on)
        if dar:
            return self.update(datas, on)
        return self.add(datas)

    def add(self, datas):
        datas = {k: str(v) if isinstance(v, int) else v for k, v in datas.items()}
        keys = ','.join(datas.keys())
        values = "','".join(datas.values())
        sql = "insert into %s (%s) values ('%s')" % (self.table, keys, values)
        self.exe(sql)
        return self.one({'id': self.cursor.lastrowid})

    def update(self, datas, on):
        fields = ','.join(["`%s`='%s'" % (k, v) for k, v in datas.items()])
        where = ' and '.join(["`%s`='%s'" % (k, v) for k, v in on.items()])
        sql = 'update %s set %s where %s' % (self.table, fields, where)
        return self.exe(sql)

    def attributes(self):
        pass

    def one(self, on):
        sql = "select * from %s" % (self.table)
        where = ' and '.join(["%s='%s'" % (k, v) for k, v in on.items()])
        if where:
            sql += ' where ' + where
        self.exe(sql)
        return self.cursor.fetchone()

    def cond(self, v):
        if isinstance(v, str) and cmp(v.upper(), 'NULL') == 0:
            return ' is NULl'
        elif isinstance(v, str) and v[0:1] in ['>', '<']:
            return "%s" % v
        elif isinstance(v, str) and v[0:2].upper() in ['OR', 'IN']:
            return " %s " % v
        else:
            return "= '%s'" % v

    def find(self, columns=('*'), on={}):
        columns = ', '.join(["%s" % column for column in columns])
        on = ' and '.join(["`%s` %s" % (k, self.cond(v)) for k, v in on.items()])
        sql = "select %s from %s" % (columns, self.table)
        if on:
            sql += " where %s " % (on)
        self.exe(sql)
        return self.cursor.fetchall()

    def exe(self, sql):
        try:
            return self.cursor.execute(sql)
        except MySQLdb.Error, e:
            print sql
            print "MySql error %d: %s" % (e.args[0], e.args[1])

    def __del__(self):
        self.cursor.close()
        self.conn.close()

if __name__ == '__main__':
    t = Dar('chuyi_cps_goods')
    on = {"id": 100}
    # datas = {"pc_popularize_url_short": 'haha.mx'}
    # print t.saveOn(datas, on);
    # print t.find(('sku_id', 'id'))
    c = Dar('chuyi_jd_category')
    on = {'jdid': 9971}
    print c.find(('id',), on)
